<template>
    <div class="upload-multiple-file">
        <el-upload :multiple="false" list-type="picture-card" :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove" action="" :file-list="fileList" :before-upload="beforeUpload"
            :http-request="uploadImage" :on-change="updateSuccess">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>

const allowType = [
    'image/png',
    'image/jpg',
    'image/jpeg',
]
export default {
    props: {
        value: {
            type: Array,
            default: () => {
                return []
            }
        },
        isUpdate: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            fileList: [],
        }
    },
    watch: {
        'value': {
            handler: function (val) {
                if (this.isUpdate) {
                    if (val.length === 0) {
                        this.fileList = [];
                    }
                    this.value.forEach((item, i) => {
                        this.fileList.push({
                            name: i,
                            url: item
                        })
                    });
                    setTimeout(() => {
                        this.$emit('update:isUpdate', false);
                    }, 1000)
                }
            },
            immediate: true
        }
    },
    methods: {
        handleRemove(file, fileList) {
            // console.log(file,fileList);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 更新父组件图片列表
        updateFatherImg(fileList) {
            console.log(fileList);
            const imgs = fileList.map(imgObj => {
                if (imgObj.url.startsWith('http')) {
                    return imgObj.url;
                }
                return imgObj.raw;
            });
            this.$emit('update:value', imgs);
        },
        updateSuccess(file, fileList) {
            this.updateFatherImg(fileList);
        },
        uploadImage(file) {
        },
        beforeUpload(file) {
            const isImg = allowType.includes(file.type);
            if (!isImg) {
                this.$message.error('只能传入图片');
                return false;
            };
            return isImg
        },

    }
}
</script>

<style lang="scss" scoped>

</style>